import React, { useState, useEffect } from 'react';
import {
    Container,
    Box,
    Typography,
    Button,
    Paper,
    Breadcrumbs,
    Link as MuiLink,
    CircularProgress,
    Alert,
    Stack
} from '@mui/material';
import {
    ArrowBack as ArrowBackIcon,
    Home as HomeIcon,
    ModelTraining as ModelIcon,
    Edit as EditIcon,
    Upload as UploadIcon
} from '@mui/icons-material';
import { Link, useNavigate, useParams } from 'react-router-dom';
import { motion } from 'framer-motion';

import { useModelContext } from '../contexts/ModelContext';
import ModelForm from '../components/ModelForm';

const ModelEdit = () => {
    const { id } = useParams();
    const navigate = useNavigate();
    const { models, loading, error, updateModel, fetchModels } = useModelContext();

    const [model, setModel] = useState(null);
    const [submitError, setSubmitError] = useState(null);
    const [notFound, setNotFound] = useState(false);

    useEffect(() => {
        if (!models || models.length === 0) {
            fetchModels();
        } else {
            // Find the model to edit
            const foundModel = models.find(m => m.id === id);
            if (foundModel) {
                setModel(foundModel);
            } else {
                setNotFound(true);
            }
        }
    }, [id, models, fetchModels]);

    const handleSubmit = async (formData) => {
        try {
            setSubmitError(null);

            // 确保表单数据包含ID
            const updateData = {
                name: formData.name,
                description: formData.description || ''
            };

            await updateModel(id, updateData);
            navigate('/models');
        } catch (err) {
            console.error('更新模型失败:', err);
            setSubmitError('更新模型失败，请稍后再试');
        }
    };

    const handleGoBack = () => {
        navigate('/models');
    };

    if (notFound) {
        return (
            <Container maxWidth="md" sx={{ py: 8, textAlign: 'center' }}>
                <Alert severity="error" sx={{ mb: 4 }}>
                    找不到ID为 {id} 的模型
                </Alert>
                <Button
                    variant="contained"
                    startIcon={<ArrowBackIcon />}
                    onClick={handleGoBack}
                >
                    返回模型列表
                </Button>
            </Container>
        );
    }

    return (
        <Container maxWidth="xl" sx={{ py: 4 }}>
            <Box sx={{ mb: 4 }}>
                <Breadcrumbs aria-label="breadcrumb" sx={{ mb: 2 }}>
                    <MuiLink
                        component={Link}
                        to="/"
                        underline="hover"
                        sx={{ display: 'flex', alignItems: 'center' }}
                    >
                        <HomeIcon sx={{ mr: 0.5 }} fontSize="inherit" />
                        首页
                    </MuiLink>
                    <MuiLink
                        component={Link}
                        to="/models"
                        underline="hover"
                        sx={{ display: 'flex', alignItems: 'center' }}
                    >
                        <ModelIcon sx={{ mr: 0.5 }} fontSize="inherit" />
                        模型列表
                    </MuiLink>
                    <Typography color="text.primary" sx={{ display: 'flex', alignItems: 'center' }}>
                        <EditIcon sx={{ mr: 0.5 }} fontSize="inherit" />
                        编辑模型
                    </Typography>
                </Breadcrumbs>

                <Paper
                    component={motion.div}
                    initial={{ opacity: 0, y: -20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.5 }}
                    elevation={0}
                    sx={{
                        p: 3,
                        backgroundImage: 'linear-gradient(120deg, #e0f7fa 0%, #bbdefb 100%)',
                        borderRadius: 4,
                        mb: 4,
                        display: 'flex',
                        justifyContent: 'space-between',
                        alignItems: 'center'
                    }}
                >
                    <Box>
                        <Typography variant="h4" component="h1" sx={{ fontWeight: 700 }}>
                            编辑模型
                        </Typography>
                        <Typography variant="body1" color="text.secondary">
                            {model ? `编辑 "${model.name}"` : '加载模型信息...'}
                        </Typography>
                    </Box>
                    <Stack direction="row" spacing={2}>
                        <Button
                            variant="contained"
                            color="primary"
                            startIcon={<UploadIcon />}
                            component={Link}
                            to={`/models/${id}/files`}
                            sx={{ display: model ? 'flex' : 'none' }}
                        >
                            文件管理
                        </Button>
                        <Button
                            variant="contained"
                            startIcon={<ArrowBackIcon />}
                            onClick={handleGoBack}
                            component={motion.button}
                            whileHover={{ scale: 1.05 }}
                            whileTap={{ scale: 0.95 }}
                        >
                            返回列表
                        </Button>
                    </Stack>
                </Paper>
            </Box>

            {loading && !model ? (
                <Box sx={{ display: 'flex', justifyContent: 'center', p: 8 }}>
                    <CircularProgress />
                </Box>
            ) : model ? (
                <ModelForm
                    initialData={model}
                    onSubmit={handleSubmit}
                    isLoading={loading}
                    error={submitError || error}
                />
            ) : null}
        </Container>
    );
};

export default ModelEdit; 